//
//  HJWebsiteFillter.m
//  KaiChat
//
//  Created by lx on 2024/3/20.
//

#import "HJWebsiteFillter.h"
#import <TFHpple.h>
#import "HJInformationPresent.h"



@interface HJWebsiteMeta: NSObject

@property (nonatomic,strong) NSString *url;
@property (nonatomic,strong) NSString *title;
@property (nonatomic,strong) NSString *icon;
@property (nonatomic,strong) NSString *desc;
@property (nonatomic, assign) BOOL isFinishi;


@end


@implementation HJWebsiteMeta


@end


@interface HJWebsiteFillter()

//0, 网络请求1, 内存, 2数据库,
@property (nonatomic,copy) void (^completedFillterBlock)(NSString *url,NSDictionary *eoj,  NSInteger loadType, NSError *error);

@end

static NSMutableDictionary *dataPools;

@implementation HJWebsiteFillter

NSMutableDictionary *getDataPools(void) {
    if (!dataPools) {
        dataPools = [NSMutableDictionary dictionary];
    }
    return dataPools;
}

- (void)webMeta:(NSString *)url {
    
    if (url && url.length > 0) {
        
        NSMutableDictionary *webObj = [getDataPools() objectForKey:url];
        if (webObj) {//正在获取链接或者有缓存
            if ([webObj[@"isFinishi"] boolValue]) {
                if (self.completedFillterBlock) {
                    self.completedFillterBlock(url, webObj, 1, nil);
                }
                return;
            }
            return;
        }
        
        webObj = [NSMutableDictionary dictionary];
        [getDataPools() setObject:webObj forKey:url];
        
        NSString *text = @"^(http|https)+.*";
        NSPredicate *regextest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", text];
        BOOL flag = [regextest evaluateWithObject:url];
        if (!flag) {
            //未携带，自己拼
            url = [NSString stringWithFormat:@"http://%@",url];
        }
        
        NSURL *URL = [NSURL URLWithString:url];
        
        //判断是否是文章的分享
        NSURL *newsShareURL = getNewsShareUrl().URL;
        if ([newsShareURL.host isEqualToString:URL.host] && [newsShareURL.path isEqualToString:URL.path]) {
            NSLog(@"文章的分享");
            NSDictionary *queryDict = [HJTools parseQueryForURL:URL];
            [HJInformationPresent loadNewswDataWithType:[queryDict[@"articleType"] intValue] newsId:toString(queryDict[@"articleId"]) complete:^(NSDictionary * _Nullable data) {
                if (data) {
        
                    [webObj setValue:@"kai" forKey:@"icon"];
                    [webObj setValue:URL.host forKey:@"url"];
                    [webObj setValue:url forKey:@"parsedUrl"];
                    [webObj setValue:[data[@"title"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:@"title"];
                    [webObj setValue:[data[@"content"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:@"description"];
                    [webObj setValue:@"1" forKey:@"isFinishi"];
                    if (self.completedFillterBlock) {
                        self.completedFillterBlock(url, webObj,2, nil);
                    }
                }
            }];
            return;
        }
     
        NSURLSession *session = [NSURLSession sharedSession];
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
        [request addValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
//        [request addValue:@"en-us" forHTTPHeaderField:@"Accept-Language"];
        request.timeoutInterval = 20;
        
//        Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36
//
         [request addValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36" forHTTPHeaderField:@"User-Agent"];
        
            NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                    
            if (error == nil && data != nil) {
                NSString *htmlString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//                NSLog(@"HTML Content: %@", htmlString);
                
                NSLog(@"获取url=%@数据完成", url);
                
                NSData *tdata = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
                
                TFHpple *doc = [[TFHpple alloc] initWithHTMLData:tdata];
                TFHppleElement *e = [[doc searchWithXPathQuery:@"//head"] firstObject];
                
                __block NSString *iconUrl = nil;
                
                [[e children] enumerateObjectsUsingBlock:^(TFHppleElement *node, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    if ([[node tagName] isEqualToString:@"link"]) {
                                       
                        NSLog(@"[node link] = %@", [node attributes]);
                        
                        if (![webObj objectForKey:@"icon"]) {
                            
                            if ([[[node attributes] objectForKey:@"rel"] isEqualToString:@"icon"] ||
                                [[[node attributes] objectForKey:@"rel"] isEqualToString:@"shortcut icon"] ||
                                [[[node attributes] objectForKey:@"rel"] isEqualToString:@"apple-touch-icon-precomposed"]) {
                                NSString *icon = [[node attributes] objectForKey:@"href"];
                                
                                if (![icon hasPrefix:@"http"]) {
                                    NSData *imageData = [[NSData alloc] initWithBase64EncodedString:icon options:NSDataBase64DecodingIgnoreUnknownCharacters];
                                    if (imageData) {
                                        [webObj setObject:icon forKey:@"icon"];
                                        [webObj setObject:@"base64" forKey:@"iconType"];
                                    } else {
                                        icon = [NSString stringWithFormat:@"http://%@%@",URL.host, icon];
                                        [webObj setObject:@"http" forKey:@"iconType"];
                                    }
                                }
                                NSLog(@"获取到icon = %@", icon);
                                [webObj setValue:icon forKey:@"icon"];
                            }
                        }
                    } if ([[[node tagName] lowercaseString] isEqualToString:@"meta"]) {
                        NSLog(@"[node attributes] = %@", [node attributes]);
                        
                        if (![webObj objectForKey:@"description"]) {
                            if ([[[[node attributes] objectForKey:@"name"] lowercaseString] isEqualToString:@"description"]) {
                                [webObj setValue:[[node attributes] objectForKey:@"content"] forKey:@"description"];
                            }
                        }
                        
                        if ([[[[node attributes] objectForKey:@"property"] lowercaseString] containsString:@"image"]) {
                           iconUrl = [[node attributes] objectForKey:@"content"];
                       } else if ([[[[node attributes] objectForKey:@"name"] lowercaseString] containsString:@"image"]) {
                           iconUrl = [[node attributes] objectForKey:@"content"];
                       }
                    } else if ([[[node tagName] lowercaseString] isEqualToString:@"title"]) {
                        [webObj setValue:[node text] forKey:[node tagName]];
                    }
                }];

                if (isEmptyString(webObj[@"icon"]) && iconUrl) {
                    [webObj setValue:iconUrl forKey:@"icon"];
                }
                
                [webObj setValue:url forKey:@"parsedUrl"];
                [webObj setValue:URL.host forKey:@"url"];
                [webObj setValue:@"1" forKey:@"isFinishi"];

                if (self.completedFillterBlock) {
                    self.completedFillterBlock(url, webObj, 2, nil);
                }
                
                NSLog(@"webObj = %@", webObj);
            } else {//查缓存的
                [getDataPools() removeObjectForKey:url];
                NSLog(@"Failed to load URL: %@", error);
            }
        }];
        [task resume];
    }
}

+ (void)websiteMeta:(NSString *)url completeHandler:(void(^)(NSString *url, NSDictionary *data, NSInteger loadType, NSError *error))completeHandler {
    HJWebsiteFillter *fillter = [[HJWebsiteFillter alloc] init];
    fillter.completedFillterBlock = completeHandler;
    [fillter webMeta:url];
}


@end
